(function () {
  var isDesktop = function () { return window.matchMedia('(min-width:1024px)').matches; };
  var KEY = 'rtdSidebarCollapsed';

  function applySavedState() {
    var saved = localStorage.getItem(KEY);
    if (saved === '1') document.body.classList.add('nav-collapsed');
  }

  function ensureButton() {
    var btn = document.querySelector('.rtd-toggle-btn');
    if (btn) return btn;

    btn = document.createElement('button');
    btn.className = 'rtd-toggle-btn';
    btn.setAttribute('type', 'button');
    document.body.appendChild(btn);
    return btn;
  }

  function updateButtonVisual(btn) {
    var collapsed = document.body.classList.contains('nav-collapsed');
    // 展开：显示“<<”，提示为“隐藏侧栏”；折叠：显示“>>”，提示为“显示侧栏”
    btn.textContent = collapsed ? '>>' : '<<';
    btn.title = collapsed ? '显示侧栏' : '隐藏侧栏';
    btn.setAttribute('aria-label', btn.title);
  }

  function onClick(btn) {
    document.body.classList.toggle('nav-collapsed');
    var collapsed = document.body.classList.contains('nav-collapsed');
    localStorage.setItem(KEY, collapsed ? '1' : '0');
    updateButtonVisual(btn);
  }

  function init() {
    if (!isDesktop()) return;    // 移动端不使用本开关

    applySavedState();

    var btn = ensureButton();
    updateButtonVisual(btn);
    btn.addEventListener('click', function () { onClick(btn); });
  }

  // 文档就绪
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  // 监控窗口变化：进出桌面断点时创建/移除按钮并清理状态
  window.addEventListener('resize', function () {
    var btn = document.querySelector('.rtd-toggle-btn');
    if (isDesktop()) {
      if (!btn) init();
    } else {
      document.body.classList.remove('nav-collapsed');
      if (btn) btn.remove();
      localStorage.removeItem(KEY);
    }
  });
})();
